package fun.ticsmyc.rpc.server;

import fun.ticsmyc.rpc.common.entity.TRPCServiceProperties;
import fun.ticsmyc.rpc.common.util.AopTargetUtils;
import fun.ticsmyc.rpc.server.annotation.TRPCInterface;
import fun.ticsmyc.rpc.server.annotation.TRPCService;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 用于在spring启动时发布服务端服务的PostProcessor
 *
 * @author Ticsmyc
 * @date 2020-11-12 9:39
 */
@Component
public class ServicePublishBeanPostProcessor implements BeanPostProcessor{
    private static final Logger logger = LoggerFactory.getLogger(ServicePublishBeanPostProcessor.class);


    @SneakyThrows
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Object target = AopTargetUtils.getTarget(bean);
        if(target.getClass().isAnnotationPresent(TRPCService.class)){
            TRPCService trpcService = target.getClass().getAnnotation(TRPCService.class);
            String group = trpcService.group();
            Class<?>[] interfaces = target.getClass().getInterfaces();
            for(Class<?> inter : interfaces){
                //解决一个实现类 实现了多个接口的问题
                if(inter.isAnnotationPresent(TRPCInterface.class)){
                    //如果这个接口标注了@TRPCInterface ，表示这个接口是基于这个实现类发布的
                    TRPCServiceProperties trpcServiceProperties = TRPCServiceProperties.builder()
                            .group(group)
                            .serviceName(inter.getCanonicalName())
                            .build();
                    ServicePublisher.publishService(bean,inter,trpcServiceProperties);
                    logger.debug("nacos：接口{}的服务{}已发布",inter.getCanonicalName(),target.getClass().getCanonicalName());
                }
            }
        }
        return bean;
    }

}
